package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import domain.User;
import repository.UserDAO;

@SuppressWarnings("unused")
@WebServlet("/Dologin")
public class Dologin extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
    public Dologin() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out= response.getWriter();
		
		UserDAO userDao = null;
		try {
			userDao = new UserDAO();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		String userId = request.getParameter("userId");
		ResultSet rs = userDao.query(userId);
		if(rs!=null){
			User user = new User();
			try {
				while(rs.next()) {
					user.setUserId(rs.getString("用户Id"));
					user.setUserName(rs.getString("用户名"));
					user.setPwd(rs.getString("密码"));
					user.setIdentity(rs.getString("用户类型"));
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			if(user.getUserId().equals(request.getParameter("userId"))&&user.getUserName().equals(request.getParameter("userName"))&&user.getPwd().equals(request.getParameter("pwd"))) {
				HttpSession session = request.getSession();
				session.setAttribute("loginUser",userId);
				session.setAttribute("identity",user.getIdentity());
				//System.out.println(session.getAttribute("identity"));
				request.getRequestDispatcher("/home.jsp").forward(request, response);
			}else{
				out.println("帐户名或密码错误，请重新登陆...");
				response.setHeader("Refresh", "3;url=login.jsp");
			}
		}else{
			out.println("此用户Id还未注册，请注册之后再登陆...");
			response.setHeader("Refresh", "3;url=register.jsp");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
